// src/main/java/com/bookmanager/controller/UserManagementController.java
package com.bookmanager.controller;

import com.bookmanager.model.User;
import com.bookmanager.service.UserService;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;
import java.io.IOException;
import java.util.List;

@WebServlet("/admin/user-management")
public class UserManagementController extends HttpServlet {
    private UserService userService = new UserService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");

        // 检查管理员权限
        if (user == null || !"admin".equals(user.getRole())) {
            response.sendRedirect("../login.jsp");
            return;
        }

        String action = request.getParameter("action");
        List<User> users;

        if ("search".equals(action)) {
            String keyword = request.getParameter("keyword");
            if (keyword != null && !keyword.trim().isEmpty()) {
                // 调用服务层方法搜索用户
                users = userService.searchUsers(keyword.trim());
                request.setAttribute("searchKeyword", keyword.trim()); // 保存搜索关键词用于前端显示
            } else {
                // 如果关键词为空，显示所有用户
                users = userService.getAllUsers();
            }
        } else {
            // 获取所有用户
            users = userService.getAllUsers();
        }

        request.setAttribute("users", users);
        request.getRequestDispatcher("/admin/user-management.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        User currentUser = (User) session.getAttribute("user");

        if (user == null || !"admin".equals(user.getRole())) {
            response.sendRedirect("../login.jsp");
            return;
        }

        if (currentUser == null || !"admin".equals(currentUser.getRole())) {
            response.sendRedirect("../login.jsp");
            return;
        }

        String action = request.getParameter("action");

        if ("updateRole".equals(action)) {
            updateUserRole(request, response);
        } else if ("search".equals(action)) {
            // 处理POST方式的搜索请求
            String keyword = request.getParameter("keyword");
            if (keyword != null && !keyword.trim().isEmpty()) {
                List<User> users = userService.searchUsers(keyword.trim());
                request.setAttribute("users", users);
                request.setAttribute("searchKeyword", keyword.trim());
                request.getRequestDispatcher("/admin/user-management.jsp").forward(request, response);
            } else {
                response.sendRedirect("user-management");
            }
        }else if ("delete".equals(action)) {
            deleteUser(request, response, currentUser);
        }
    }

    private void updateUserRole(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            String userId = request.getParameter("userId");
            String newRole = request.getParameter("role");

            // 调用服务层方法更新用户角色
            boolean success = userService.updateUserRole(userId, newRole);

            if (success) {
                // 返回成功响应
                response.setStatus(HttpServletResponse.SC_OK);
                response.getWriter().write("success");
            } else {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                response.getWriter().write("update_failed");
            }

        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.getWriter().write("system_error");
        }
    }

    /**
     * 删除用户处理方法
     */
    private void deleteUser(HttpServletRequest request, HttpServletResponse response, User currentUser) throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

        System.out.println("🔍 开始处理删除请求");

        try {
            String userId = request.getParameter("userId");
            String forceDelete = request.getParameter("forceDelete");

            System.out.println("📝 删除参数 - userId: " + userId + ", forceDelete: " + forceDelete);
            System.out.println("👤 当前操作管理员: " + currentUser.getUserId());

            if (userId == null || userId.trim().isEmpty()) {
                System.out.println("❌ 用户ID为空");
                sendErrorResponse(response, "用户ID不能为空");
                return;
            }

            String result;
            if ("true".equals(forceDelete)) {
                System.out.println("🚨 执行强制删除");
                result = userService.forceDeleteUser(userId, currentUser.getUserId());
            } else {
                System.out.println("🔧 执行普通删除");
                result = userService.deleteUser(userId, currentUser.getUserId());
            }

            System.out.println("✅ 删除结果: " + result);

            if ("success".equals(result)) {
                sendSuccessResponse(response, "用户删除成功");
            } else {
                sendErrorResponse(response, result);
            }

        } catch (Exception e) {
            System.out.println("❌ 删除过程出现异常: " + e.getMessage());
            e.printStackTrace();
            sendErrorResponse(response, "系统错误: " + e.getMessage());
        }
    }

    /**
     * 发送成功响应
     */
    private void sendSuccessResponse(HttpServletResponse response, String message) throws IOException {
        response.setStatus(HttpServletResponse.SC_OK);
        response.getWriter().write("{\"success\": true, \"message\": \"" + message + "\"}");
    }

    /**
     * 发送错误响应
     */
    private void sendErrorResponse(HttpServletResponse response, String message) throws IOException {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        response.getWriter().write("{\"success\": false, \"message\": \"" + message + "\"}");
    }
}